/**
 * <p/>
 * 实现功能：权限对象类型
 * <p/>
 *
 * @author 李艳
 */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Button, Checkbox, Input, message, Modal } from 'antd';
import SimpleTable from "../../../commons/components/SimpleTable";
import { hide, show } from "../../../configs/SharedReducer";
import { deleteCorp, getAllAuthorizeEntityType, save } from "./AuthorizeEntityTypeService";
import { searchListByKeyWithTag } from "../../../commons/utils/CommonUtils";
import AuthorizeEntityTypeModal from "./AuthorizeEntityTypeModal";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import PageOperateHoc from "../../../commons/components/PageOperateHoc/index.jsx";
import CheckAuth from "../../../commons/components/CheckAuth/index.jsx";

const Search = Input.Search;
const confirm = Modal.confirm;
class AuthorizeEntityTypeTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      modalVisible: false,
      confirmLoading: false,
      selectedRows: [],
      isAdd: false
    };
  }

  componentWillMount() {
    this.getDataSource()
  }

  onRef = (ref) => {
    this.ref = ref
  };
  getDataSource = () => {
    this.props.show();
    getAllAuthorizeEntityType().then(data => {
      this.setState({ data, selectedRows: [], searchValue: "" })
    }).catch(e => {
    }).finally(() => {
      this.props.hide();
    })
  };

  handleRowSelectChange = (selectedRows) => {
    this.setState({ selectedRows })
  };
  handleModalVisible = (modalVisible, isAdd = this.state.isAdd) => {
    this.setState({ modalVisible, isAdd })
  };
  addClick = () => {
    this.handleModalVisible(true, true)
  };
  editClick = (record) => {
    this.setState({ editData: record });
    this.handleModalVisible(true, false)
  };
  handleSave = () => {
    this.ref.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = {}
        Object.assign(params, values);
        if (this.state.isAdd)
          delete params.id;//新增时id==="",保存可能会出错，需删除id
        this.setState({ confirmLoading: true });
        save(params).then(result => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "请求成功");
            //刷新本地数据
            this.getDataSource();
            this.setState({ confirmLoading: false, modalVisible: false });
          } else {
            message.error(result.message ? result.message : "请求失败");
            this.setState({ confirmLoading: false});
          }
        }).catch(e => {
          this.setState({ confirmLoading: false });
        })
      }
    })
  };
  judgeSelected = () => {
    if (this.state.selectedRows.length === 0) {
      message.error("请选择一行数据！");
      return false
    }
    return true
  };

  handleModalCancel = () => {
    this.handleModalVisible(false)
  };

  handleSearch = (value) => {
    searchListByKeyWithTag(this.state.data, { keyword: value }).then(data => {
      this.setState({ data, searchValue: value })
    })
  };

  deleteClick = (record) => {
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        let params = {};
        params = record.id;
        thiz.props.show();
        deleteCorp(params).then(result => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "请求成功");
            //刷新本地数据
            thiz.getDataSource();
          } else {
            message.error(result.message ? result.message : "请求失败");
          }
        }).catch(e => {
        }).finally(() => {
          thiz.props.hide();
        })
      }
    });
  };

  render() {
    const columns = [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth operateCode="BASIC-HTPZ-AUTHENTITYTYPE-EDIT">
                <a className={'row-operator-item'} onClick={() => this.editClick(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth operateCode="BASIC-HTPZ-AUTHENTITYTYPE-DELETE" >
                <a className={'row-operator-item'} onClick={() => this.deleteClick(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '应用模块',
        dataIndex: 'appModule.name',
        width: 200,
      },
      {
        title: '实际类名',
        dataIndex: 'entityClassName',
        width: 240,
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 200
      },
      {
        title: 'api服务路径',
        dataIndex: 'apiPath',
        width: 180
      },
      {
        title: '树形结构',
        dataIndex: 'beTree',
        width: 100,
        render: (text, record, index) => (
          <div style={{ textAlign: "center" }}>
            <Checkbox checked={record.beTree} disabled />
          </div>
        ),
      },
    ];

    const title = () => {
      return [
        <CheckAuth
          operateCode="BASIC-HTPZ-AUTHENTITYTYPE-ADD"
          key="edit"
        >
          <Button type={"primary"} className={"primaryButton"} onClick={this.addClick}>新增</Button>
        </CheckAuth>
      ]

    };

    //表头搜索框
    const search = () => {
      return [
        <Search
          key="search"
          placeholder="输入关键字查询"
          onSearch={value => this.handleSearch(value)}
          style={{ width: 220 }}
          allowClear
        />
      ]
    };

    return (
      <HeadBreadcrumb>
        <div className={"tbar-table"}>
          <div className={'tbar-box'}>
            <div className={'tbar-btn-box'}>{title()}</div>
            <div className={'tbar-search-box'}>{search()}</div>
          </div>
          <SimpleTable
            rowsSelected={this.state.selectedRows}
            onSelectRow={this.handleRowSelectChange}
            data={this.state.searchValue ? this.state.data.filter(item => item.tag === true) : this.state.data}
            columns={columns}
          />
        </div>
        <AuthorizeEntityTypeModal
          isAdd={this.state.isAdd}
          modalVisible={this.state.modalVisible}
          confirmLoading={this.state.confirmLoading}
          handleOk={this.handleSave}
          handleCancel={this.handleModalCancel}
          onRef={this.onRef}
          defaultValue={this.state.editData ? this.state.editData : {}} />
      </HeadBreadcrumb>
    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(AuthorizeEntityTypeTable))



